package com.pospi.xstore.ui.pay_ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.dao.OrderDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.CouponsBeen;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.OrderBeen;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.dto.PayBeen;
import com.pospi.xstore.dto.ReturnDto;
import com.pospi.xstore.dto.Tablebeen;
import com.pospi.xstore.greendao.OrderBeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.http.UploadData;
import com.pospi.xstore.ui.CaptureActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.cash_ui.ScanReceiptActivity;
import com.pospi.xstore.ui.vip_ui.CountponsActivity;
import com.pospi.xstore.ui.vip_ui.VipBeen;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;
import com.tsy.sdk.myokhttp.response.RawResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends BaseActivity {
//
//    @Bind(R.id.tv_vip_favour)
//    TextView tvVipFavour;
//    @Bind(R.id.tv_offline_favour)
//    TextView tvOfflineFavour;
    @Bind(R.id.tv_due1)
    TextView tvDue1;//应收金额1
    @Bind(R.id.iv_cash)
    ImageView ivCash;
    @Bind(R.id.ll_cash)
    LinearLayout llCash;
    @Bind(R.id.iv_bankCard)
    ImageView ivBankCard;
    @Bind(R.id.ll_bankCard)
    LinearLayout llBankCard;
    @Bind(R.id.iv_weiXin)
    ImageView ivWeiXin;
    @Bind(R.id.ll_weiXin)
    LinearLayout llWeiXin;
    @Bind(R.id.iv_alipay)
    ImageView ivAlipay;
    @Bind(R.id.ll_alipay)
    LinearLayout llAlipay;
    @Bind(R.id.iv_integral)
    ImageView ivIntegral;
    @Bind(R.id.ll_integral)
    LinearLayout llIntegral;
    @Bind(R.id.iv_other)
    ImageView ivOther;
    @Bind(R.id.ll_other)
    LinearLayout llOther;
    @Bind(R.id.tv_actual)
    TextView tvActual;//实收金额
    @Bind(R.id.tv_due2)
    TextView tvDue2;//应收金额2
    @Bind(R.id.tv_change)
    TextView tvChange;//找零
    @Bind(R.id.tv_settle)
    TextView tvSettle;
    @Bind(R.id.et_ss)
    EditText etSs;
    @Bind(R.id.pay_list)
    ListView pay_list;
    @Bind(R.id.tv_yh)
    TextView tv_yh;

    private double ysMoney;

    private double zlMoney;
    private double ssMoney;

    private int PayWay;
    private String maxNO;
    private String goodsInfo;
    private String payWayString;
    private String cashier_name;
    private String shopId;

    public final static String PUT_MAXNO = "maxNo";
    public final static String PUT_YS = "ys";
    public final static String PUT_SS = "sss";
    public final static String PUT_ZL = "zl";
    public final static String PUT_PAYWAY = "payway";

    private static final int PAYSUCCESS = 1;
    private static final int PAYFAIL = 0;
    private static final int PAYERROR = -1;
    private static final int TIMEOUT = 9;

    private static final int HXCG = 11;
    private static final int HXSP = 12;

    public static final int LAKALA = 444;
    /******
     * 卡支付
     */
    public static final String pay_tp_card = "0";

    /***
     * 扫码支付
     */
    public static final String pay_tp_scan = "1";

    /**
     * 消费
     */
    public static final String proc_cd_spend = "000000";
    /**
     * 消费撤销
     */
    public static final String proc_cd_spend_remove = "200000";
    /**
     * 扫码支付
     */
    public static final String proc_cd_scan = "660000";
    /**
     * 扫码撤销
     */
    public static final String proc_cd_scan_remove = "680000";
    /**
     * 扫码补单
     */
    public static final String proc_cd_scan_budan = "700000";
    /**
     * 结算
     */
    public static final String proc_cd_jiesuan = "900000";
    private String cashier_number;
    private Tablebeen tablebeen;
    private String vip = "";

    private VipBeen vipBeen;
    /**
     * 处理微信，支付宝支付结果
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PAYSUCCESS:
                    closeDialog();
                    paySuccess();
                    break;
                case PAYFAIL:
                    closeDialog();
                    Toast.makeText(PayActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case PAYERROR:
                    closeDialog();
                    Toast.makeText(PayActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case TIMEOUT:
                    closeDialog();
                    Toast.makeText(PayActivity.this, "服务器请求失败，请稍后重试！", Toast.LENGTH_SHORT).show();
                    break;

                case HXCG:
                    addPay(Constant.PAYMENT_OTHER, Constant.PAYMENT_OTHER_String, denomination);
                    Toast.makeText(PayActivity.this, "核销成功", Toast.LENGTH_SHORT).show();
                    break;
                case HXSP:
                    Toast.makeText(PayActivity.this, "核销失败", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    private List<PayBeen> payBeens;
    private MyAdapter adapter;
    private String denomination;
    private double proReduce;
    private List<GoodsDto> goodsDtos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_pay);
        setTitle("付款");
        ButterKnife.bind(this);
        setMenuImage(R.drawable.icon_yhq_scan);

        vipBeen = (VipBeen) getIntent().getSerializableExtra("vip");
        if (vipBeen != null) {
            vip = vipBeen.getId();
        }

        PayWay = Constant.PAYMENT_CASH;
        payWayString = Constant.PAYMENT_CASH_String;
        ysMoney = DoubleSave.doubleSaveTwo(getIntent().getDoubleExtra(ScanReceiptActivity.PUT_MONEY, 0));
        String prodicount = getIntent().getStringExtra("pro");
        if (prodicount.contains("%")) {
            proReduce = DoubleSave.doubleSaveTwo((1 - Double.parseDouble(prodicount.substring(0, prodicount.length() - 1)) / 100) * ysMoney);
        } else {
            proReduce = DoubleSave.doubleSaveTwo(Double.parseDouble(prodicount));
        }
        setGoodsTitalDiscount(proReduce);
        ysMoney = DoubleSave.doubleSaveTwo(ysMoney - proReduce);
        tv_yh.setText(proReduce+"");

        maxNO = getIntent().getStringExtra(ScanReceiptActivity.PUT_MAXNO);
        tablebeen = (Tablebeen) getIntent().getSerializableExtra("tableBeen");

        Log.i("table", tablebeen.getNumber() +"------------"+ tablebeen.getTId());
        tvDue1.setText(String.valueOf(DoubleSave.doubleSaveTwo(ysMoney + proReduce)));
        tvDue2.setText(String.valueOf(ysMoney));

        init();

        goodsInfo = getSharedPreferences("goodsdto_json", MODE_PRIVATE).getString("json", null);
        goodsDtos = SaveOrderInfo.changeToList(goodsInfo);
//        int whichOne = getSharedPreferences("islogin", MODE_PRIVATE).getInt("which", 0);
        cashier_name = "";
        cashier_number = "";

        shopId = SPHelper.getInstance().getString(Constant.STORE_ID);

    }

    //将优惠金额平分到每个商品上
    private void setGoodsTitalDiscount(double proReduce) {
        if (proReduce != 0) {
            proReduce = proReduce /Double.parseDouble(tvDue1.getText().toString());
            for (GoodsDto dto : goodsDtos) {
                dto.setCxzk(DoubleSave.doubleSaveTwo(proReduce*dto.getNum()*dto.getPrice()));
            }
        }

    }
    //将优惠金额平分到每个商品上
    private void setGoodsTitalDiscount2(double proReduce) {
        if (proReduce != 0) {
            proReduce = proReduce /Double.parseDouble(tvDue1.getText().toString());
            for (GoodsDto dto : goodsDtos) {
                dto.setLszk(DoubleSave.doubleSaveTwo(proReduce*dto.getNum()*dto.getPrice()));
            }
        }

    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        if (vipBeen == null) {
            Toast.makeText(this, "当前不是会员", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(PayActivity.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.YHQ);
    }

    public void init() {
        payBeens = new ArrayList<>();
        adapter = new MyAdapter();
        pay_list.setAdapter(adapter);

        ssMoney = ysMoney;
        zlMoney = DoubleSave.doubleSaveTwo(ssMoney - ysMoney);
        if (zlMoney >= 0) {
            tvChange.setText(String.valueOf(zlMoney));
        } else {
            showToast("请输入正确的实收金额");
            tvChange.setText("0");
        }
        setJeDetail();
    }
    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return payBeens.size();
        }

        @Override
        public Object getItem(int i) {
            return payBeens.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(PayActivity.this).inflate(R.layout.sup_list_item, null);
                holder.tv = view.findViewById(R.id.sup_item);
                view.setTag(holder);

            } else {
                holder = (Holder) view.getTag();
            }
            DecimalFormat decimalFormat = new DecimalFormat("######.##########");
            holder.tv.setText(payBeens.get(i).getName() + ":       " + decimalFormat.format(Double.parseDouble(payBeens.get(i).getSs())));

            return view;
        }
        class Holder{
            TextView tv;
        }
    }

    private CouponsBeen couponsBeen;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        CouponsBeen cou = (CouponsBeen) intent.getSerializableExtra("yhq");
        if (cou != null && cou.getId() != null) {
            couponsBeen = cou;
            addPay(Constant.PAYMENT_OTHER,Constant.PAYMENT_OTHER_String,couponsBeen.getDenomination());
        }

    }

    @Override
    protected void onStart() {
        super.onStart();

//        etSs.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (!etSs.getText().toString().isEmpty()) {
//                    ssMoney = DoubleSave.doubleSaveTwo(Double.parseDouble(etSs.getText().toString()));
//                    if (ssMoney >= ysMoney) {
//                        tvActual.setText(etSs.getText().toString());
//                        zlMoney = DoubleSave.doubleSaveTwo(ssMoney - ysMoney);
//                        tvChange.setText(String.valueOf(zlMoney));
//                    }
//                } else {
//                    init();
//                }
//            }
//        });

    }

    private EditText et_zr;
    private EditText et_zk;
    public void showdicountDialog() {


        new CircleDialog.Builder(this)
                .setBodyView(R.layout.dialog_single_discount, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        LinearLayout ll_sl = view.findViewById(R.id.ll_sl);
                        ll_sl.setVisibility(View.GONE);
                        et_zr = view.findViewById(R.id.et_zr);
                        et_zk = view.findViewById(R.id.et_zk);
                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        String zr = et_zr.getText().toString().trim();
                        String zk = et_zk.getText().toString().trim();
                        if (!zk.isEmpty() && !zr.isEmpty()) {
                            Toast.makeText(PayActivity.this, "请选择一种优惠", Toast.LENGTH_SHORT).show();
                        } else if (zk.isEmpty() && zr.isEmpty()) {

                        } else {
                            try {
                                if (zr.isEmpty()) {
                                    zr = "0";
                                }
                                if (zk.isEmpty()) {
                                    zk = "1";
                                } else {
                                    zr = String.valueOf((Double.parseDouble(zk) / 100) * ysMoney);
                                }
                                if (Double.parseDouble(zr) > ysMoney) {
                                    Toast.makeText(PayActivity.this, "折扣金额不能大于商品总价", Toast.LENGTH_SHORT).show();
                                } else {
                                    ysMoney = Double.parseDouble(tvDue1.getText().toString().trim());
                                    proReduce = DoubleSave.doubleSaveTwo(Double.parseDouble(zr));
                                    ysMoney = DoubleSave.doubleSaveTwo(ysMoney - proReduce);
                                    setJeDetail();
                                    tv_yh.setText(proReduce + "");
                                    setGoodsTitalDiscount2(proReduce);
                                }
                            } catch (Exception e) {
                                Toast.makeText(PayActivity.this, "请输入正确的折让", Toast.LENGTH_SHORT).show();
                            }

                        }

                    }
                })
                .setCancelable(false)
                .setTitle("整单优惠")
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                })
                .show();
    }

    private boolean noChoose = false;

    @OnClick({  R.id.ll_cash, R.id.ll_bankCard, R.id.ll_weiXin, R.id.ll_alipay, R.id.ll_integral, R.id.ll_other, R.id.tv_settle,R.id.tv_cz,R.id.iv_discount})
    public void onClick(View view) {
        String ss = etSs.getText().toString().trim();
        switch (view.getId()) {
            case R.id.iv_discount:
                showdicountDialog();
                break;
            case R.id.tv_cz:
                //重置支付方式
                noChoose = false;
                llCash.setClickable(true);

                payBeens.clear();
                adapter.notifyDataSetChanged();
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                setJeDetail();
                break;
            case R.id.ll_cash:
                if (noChoose||noMoney()) {
                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (payBeens.size() == 0) {
                    if (ss.isEmpty()) {
                        addPay(Constant.PAYMENT_CASH, Constant.PAYMENT_CASH_String, String.valueOf(ysMoney));
                    } else {
                        addPay(Constant.PAYMENT_CASH, Constant.PAYMENT_CASH_String, String.valueOf(Double.parseDouble(ss)));
                    }
                } else {

                    if (ss.isEmpty()) {
                        addPay(Constant.PAYMENT_CASH, Constant.PAYMENT_CASH_String, String.valueOf(getLastMoney()));
                    } else {
                        addPay(Constant.PAYMENT_CASH, Constant.PAYMENT_CASH_String, String.valueOf(Double.parseDouble(ss)));
                    }
                }


                llCash.setClickable(false);

                etSs.setText("");

                ivCash.setImageResource(R.drawable.icon_xjl);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_CASH;
                payWayString = Constant.PAYMENT_CASH_String;

                break;
            case R.id.ll_bankCard:
                if (noChoose||noMoney()) {
                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (payBeens.size() == 0) {
                    addPay(Constant.PAYMENT_BANK_CARD, Constant.PAYMENT_BANK_CARD_String, String.valueOf(ysMoney));
                } else {
                    addPay(Constant.PAYMENT_BANK_CARD, Constant.PAYMENT_BANK_CARD_String, String.valueOf(getLastMoney()));
                }
                noChoose = true;

                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_BANK_CARD;
                payWayString = Constant.PAYMENT_BANK_CARD_String;
                break;
            case R.id.ll_weiXin:
                if (noChoose||noMoney()) {
                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (payBeens.size() == 0) {
                    addPay(Constant.PAYMENT_WEIXIN, Constant.PAYMENT_WEIXIN_String, String.valueOf(ysMoney));
                } else {
                    addPay(Constant.PAYMENT_WEIXIN, Constant.PAYMENT_WEIXIN_String, String.valueOf(getLastMoney()));
                }
                noChoose = true;
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wxl);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_WEIXIN;
                payWayString = Constant.PAYMENT_WEIXIN_String;
                break;
            case R.id.ll_alipay:
                if (noChoose||noMoney()) {
                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (payBeens.size() == 0) {
                    addPay(Constant.PAYMENT_ALIPAY, Constant.PAYMENT_ALIPAY_String, String.valueOf(ysMoney));
                } else {
                    addPay(Constant.PAYMENT_ALIPAY, Constant.PAYMENT_ALIPAY_String, String.valueOf(getLastMoney()));
                }
                noChoose = true;
                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfb);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_ALIPAY;
                payWayString = Constant.PAYMENT_ALIPAY_String;
                break;
            case R.id.ll_integral:
                if (vipBeen == null) {
                    Toast.makeText(this, "当前不是会员", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (noChoose||noMoney()) {
                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Double.parseDouble(vipBeen.getJfye()) == 0) {
                    Toast.makeText(this, "无可用积分", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (payBeens.size() == 0) {
                    addPay(Constant.PAYMENT_INTEGAL, Constant.PAYMENT_INTEGAL_String, vipBeen.getJfye());
                } else {
                    if (Double.parseDouble(vipBeen.getJfye()) >= getLastMoney()) {
                        addPay(Constant.PAYMENT_INTEGAL, Constant.PAYMENT_INTEGAL_String, vipBeen.getJfye());
                    } else {
                        Toast.makeText(this, "积分余额不足", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fk);
                ivOther.setImageResource(R.drawable.icon_qtn);
                PayWay = Constant.PAYMENT_INTEGAL;
                payWayString = Constant.PAYMENT_INTEGAL_String;
                break;
            case R.id.ll_other:
                if (vipBeen == null) {
                    Toast.makeText(this, "当前不是会员", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(PayActivity.this, CountponsActivity.class);
                intent.putExtra("vipid", vipBeen.getId());
                startActivity(intent);

//                if (noChoose||noMoney()) {
//                    Toast.makeText(this, "请支付", Toast.LENGTH_SHORT).show();
//                    return;
//                }

                ivCash.setImageResource(R.drawable.icon_xj);
                ivBankCard.setImageResource(R.drawable.icon_yh2);
                ivWeiXin.setImageResource(R.drawable.icon_wx);
                ivAlipay.setImageResource(R.drawable.icon_zfbh);
                ivIntegral.setImageResource(R.drawable.icon_fkh);
                ivOther.setImageResource(R.drawable.icon_qty);
                PayWay = Constant.PAYMENT_OTHER;
                payWayString = Constant.PAYMENT_OTHER_String;
                break;
            case R.id.tv_settle://开始结账
                if (Double.parseDouble(tvActual.getText().toString()) >= ysMoney) {
                    startPay();
                } else {
                    Toast.makeText(this, "支付金额应大于应收金额", Toast.LENGTH_SHORT).show();
                }

//                switch (PayWay) {
//                    case Constant.PAYMENT_ALIPAY:
////
////                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
////                            diaoyong(pay_tp_scan, proc_cd_scan);
////                        } else {
//                        Intent intent1 = new Intent(PayActivity.this, CaptureActivity.class);
//                        startActivityForResult(intent1, Constant.PAYMENT_ALIPAY);
////                        }
//                        break;
//                    case Constant.PAYMENT_WEIXIN:
////                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
////                            diaoyong(pay_tp_scan, proc_cd_scan);
////                        } else {
//                        Intent intent2 = new Intent(PayActivity.this, CaptureActivity.class);
//                        startActivityForResult(intent2, Constant.PAYMENT_WEIXIN);
////                        }
//                        break;
//                    case Constant.PAYMENT_BANK_CARD:
//                        if (android.os.Build.MODEL.equals(Constant.MODEL_LAKALA)) {
//                            diaoyong(pay_tp_card, proc_cd_spend);
//                        } else {
//                            showToast("该功能请等待");
//                        }
//                        break;
//                    default:
//                        addOrderToDB(null);
//                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
//                        intent.putExtra(PUT_PAYWAY, payWayString);
//                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
//                        intent.putExtra(PUT_ZL, tvChange.getText().toString());
//                        intent.putExtra(PUT_SS, tvActual.getText().toString());
//                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
//                        startActivity(intent);
//                        finish();
//                        break;
//
//                }
//                break;
        }
    }

    private String payMoney = "";

    //开始结账
    private void startPay() {
        int type = 0;


        for (PayBeen been : payBeens) {
            type = Constant.PAYMENT_CASH;
            if (been.getName().equals(Constant.PAYMENT_ALIPAY_String)) {
                type = Constant.PAYMENT_ALIPAY;
                payMoney = been.getSs();

            } else if (been.getName().equals(Constant.PAYMENT_WEIXIN_String)) {
                type = Constant.PAYMENT_WEIXIN;
                payMoney = been.getSs();

            } else if (been.getName().equals(Constant.PAYMENT_BANK_CARD_String)) {
                type = Constant.PAYMENT_BANK_CARD;
            }
        }
        switch (type) {
            case Constant.PAYMENT_CASH:
                paySuccess();
                break;
            case Constant.PAYMENT_ALIPAY:
                Intent intent1 = new Intent(PayActivity.this, CaptureActivity.class);
                startActivityForResult(intent1, Constant.PAYMENT_ALIPAY);
                break;
            case Constant.PAYMENT_WEIXIN:
                Intent intent2 = new Intent(PayActivity.this, CaptureActivity.class);
                startActivityForResult(intent2, Constant.PAYMENT_WEIXIN);
                break;
            case Constant.PAYMENT_BANK_CARD:
                Toast.makeText(this, "暂不支持该付款方式", Toast.LENGTH_SHORT).show();
                break;

        }

    }

    //添加付款
    private void addPay(int paymentCash, String payment_cash_string, String s) {
        PayBeen been = new PayBeen();
        been.setId(String.valueOf(paymentCash));
        been.setName(payment_cash_string);
        been.setSs(s);
        payBeens.add(been);
        adapter.notifyDataSetChanged();
        setJeDetail();

    }
    private double getLastMoney(){
        double je = 0;
        for (PayBeen been : payBeens) {
            je += Double.parseDouble(been.getSs());
        }
        if (ysMoney > je) {
            return DoubleSave.doubleSaveTwo(ysMoney - je);
        } else {
            return 0.0;
        }
    }
    private double getzlMoney(){
        double je = 0;
        for (PayBeen been : payBeens) {
            je += Double.parseDouble(been.getSs());
        }
        if (ysMoney > je) {
            return 0.0;
        } else {
            return DoubleSave.doubleSaveTwo(je - ysMoney);
        }
    }
    private boolean noMoney(){
        double je = 0;
        for (PayBeen been : payBeens) {
            je += Double.parseDouble(been.getSs());
        }
        if (ysMoney > je) {
            return false;
        } else {
            return true;
        }
    }

    public void paySuccess(){
        if (vipBeen != null && couponsBeen != null) {
            desYHQ(couponsBeen.getNo(), vipBeen.getId());
        }


        String way = "";
        for (PayBeen been : payBeens) {
            way += been.getName()+" ";
        }

        addOrder(null);
        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
        intent.putExtra(PUT_PAYWAY, way);
        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
        intent.putExtra(PUT_ZL, "0.0");
        intent.putExtra(PUT_SS, tvActual.getText().toString());
        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
        startActivity(intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String code = null;
        switch (requestCode) {
            case LAKALA:
                switch (resultCode) {
                    //支付成功
                    case Activity.RESULT_OK:
                        addOrder(null);
                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                        intent.putExtra(PUT_PAYWAY, payWayString);
                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_ZL, "0.0");
                        intent.putExtra(PUT_SS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
                        startActivity(intent);
                        finish();
                        break;
                    // 支付取消
                    case Activity.RESULT_CANCELED:
                        Bundle bundle = data.getExtras();
                        String reason = bundle.getString("reason");
                        if (reason != null) {
                            showToast("支付取消" + reason);
                        }
                        break;
                    case -2:
                        // 交易失败
                        Bundle bundle1 = data.getExtras();
                        String reason1 = bundle1.getString("reason");
                        if (reason1 != null) {
                            showToast(reason1);
                        }
                        break;

                }
                break;
            case Constant.PAYMENT_ALIPAY:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
//                        requestPay(code, "ali");
                        unionPay(code, "1", String.valueOf(maxNO));
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("支付失败，未获取到条形码");
                }

                break;
            case Constant.PAYMENT_WEIXIN:
                try {
                    code = data.getStringExtra("code");
                    if (!code.isEmpty()) {
                        unionPay(code, "1", String.valueOf(maxNO));
//                        requestPay(code, "wx");
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("支付失败，未获取到条形码");
                }
                break;
            case Constant.YHQ://核销优惠券
                try {
                    String yhq_code = data.getStringExtra("code");
                    if (!yhq_code.isEmpty()) {
                        serachYHQ(yhq_code ,vipBeen.getId());
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    showToast("未获取到条形码");
                }

                break;

        }
    }

    //优惠券核销
    private void serachYHQ(String yhq_code ,String vipid) {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "vip.vvip");
        params.put("fun", "destroycoupon");
        params.put("vid", vipid);
        params.put("no", yhq_code);
        params.put("mid", SPHelper.getInstance().getString(Constant.STORE_ID));
        Log.i("desto", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    Log.i("re", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    final String err = object.getString("errMsg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PayActivity.this, err, Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.i("re", object.getString("errMsg"));
                    if (object.getString("errCode").equals("100")) {
                        denomination = object.getJSONObject("result").getString("denomination");
                        Message message = Message.obtain();
                        message.what = HXCG;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = HXSP;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }

    //优惠券核销
    private void desYHQ(String yhq_code ,String vipid) {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "vip.vvip");
        params.put("fun", "destroycoupon");
        params.put("vid", vipid);
        params.put("no", yhq_code);
        params.put("mid", SPHelper.getInstance().getString(Constant.STORE_ID));
        Log.i("desto", params.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    Log.i("re", new String(bytes));
                    JSONObject object = new JSONObject(new String(bytes));
                    final String err = object.getString("errMsg");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PayActivity.this, err, Toast.LENGTH_SHORT).show();
                        }
                    });
                    Log.i("re", object.getString("errMsg"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }

    /**
     * 开始调用拉卡拉支付
     *
     * @param pay_tp
     * @param proc_cd
     */

    public void diaoyong(String pay_tp, String proc_cd) {
        try {
            ComponentName componet = new ComponentName("com.lkl.cloudpos.payment", "com.lkl.cloudpos.payment.activity.MainMenuActivity");
            Intent intent = new Intent();
            intent.setComponent(componet);
            Bundle bundle = new Bundle();
            bundle.putString("msg_tp", "0200");//固定值，请求
            bundle.putString("pay_tp", pay_tp);//0是银行卡，1是扫码
            bundle.putString("proc_tp", "00");//00代表是消费
            bundle.putString("proc_cd", proc_cd);//交易处理码
            bundle.putString("amt", String.valueOf(ysMoney));//金额
            bundle.putString("order_no", String.valueOf(maxNO));//订单号
            bundle.putString("appid", this.getPackageName());//调用者应用包名
            bundle.putString("time_stamp", GetData.getYYMMDDHHMMSSNoSpellingTime());//得到现在的时间
            bundle.putString("order_info", "扫码支付");//订单的信息
            intent.putExtras(bundle);
            this.startActivityForResult(intent, LAKALA);
        } catch (ActivityNotFoundException
                e) {
            //TODO:
        } catch (Exception e) {
            //TODO
        }
    }

    /**
     * 请求支付
     *
     * @param barcode 条形码
     * @param way     传送给服务器的支付方式
     * @param name    支付成功后告诉用户的支付方式
     */
    private String out_trade_no = null;

    public void requestPay(String barcode, final String way) {
        //得到现在进行请求的是支付宝还是微信
        showDialog("正在请求支付");

        SharedPreferences preferences = getSharedPreferences("Token", MODE_PRIVATE);
        String aa = preferences.getString("value", "");
        String[] names = aa.split("\\,");
        String deviceNo = names[2];//收银机号
        String user_Id = names[3];//用户ID
        String ServerNo = names[4];//服务器号
        String uid = names[1];

        String now = GetData.getHHmmssTime();
        Log.i("获取到的当前时间", now);
        out_trade_no = String.valueOf(maxNO) + deviceNo + now + user_Id + ServerNo;//交易号
        Log.i("out_trade_no", out_trade_no);

        RequestParams payParamsMaps = new RequestParams();
        payParamsMaps.put("auth_code", barcode);//扫描到的条形码数据
        payParamsMaps.put("body", "统销商品自定义价格");//死数据
        payParamsMaps.put("pay_mode", way);//支付方式,支付宝或者是微信
        payParamsMaps.put("fee", getPayMoney(way));//订单的金额
        payParamsMaps.put("out_trade_no", out_trade_no);//交易号
        payParamsMaps.put("uid", uid);//用户的id
        Log.i("pay", payParamsMaps.toString());

        AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("onSuccess", new String(bytes));

                ReturnDto returnDto = new ReturnDto();

                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    returnDto.setResult(object.getInt("Result"));
                    returnDto.setMessage(object.getString("Message"));
                    returnDto.setValue(String.valueOf(object.getString("Value")));
                    closeDialog();
                    if (returnDto.getResult() == 1) {
                        addOrder(returnDto.getValue());
                        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                        intent.putExtra(PUT_PAYWAY, payWayString);
                        intent.putExtra(PUT_YS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_ZL, "0.0");
                        intent.putExtra(PUT_SS, String.valueOf(ysMoney));
                        intent.putExtra(PUT_MAXNO, String.valueOf(maxNO));
                        startActivity(intent);
                        finish();
                    } else {
                        showToast(returnDto.getMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                ReturnDto returnDto = new ReturnDto();

                closeDialog();
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    returnDto.setResult(object.getInt("Result"));
                    returnDto.setMessage(object.getString("Message"));
                    returnDto.setValue(String.valueOf(object.getInt("Value")));
                    closeDialog();
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("请求失败，请稍后重试");
                }
            }
        };
        LoadServer.getConnect(getApplicationContext(), Api.PAYMENT, payParamsMaps, handler);
    }

    public String getPayMoney(String way) {
        String payMoney = null;

        if (way.equals("wx")) {
            payMoney = String.valueOf((int) (ysMoney * 100));
        } else if (way.equals("ali")) {
            payMoney = String.valueOf(ysMoney);
        }
        return payMoney;
    }

    private Dialog waitingDialog;

    public void showDialog(String msg) {
        if (waitingDialog == null) {
            waitingDialog = WaitingDialog.createLoadingDialog(this, msg);
            waitingDialog.show();
        }
    }

    public void closeDialog() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
    }

    public void addOrder(String aliPayNumber) {

        OrderBeenDao dao = App.getInstance().getDaoSession().getOrderBeenDao();
        OrderBeen orderDto = new OrderBeen();
        orderDto.setOrder_info(SaveOrderInfo.changeGoodDtoToJson(goodsDtos));//存储的该订单的商品的信息
        orderDto.setPayway(SaveOrderInfo.changePaytoToJson(payBeens));//支付列表
        orderDto.setTime(GetData.getYYMMDDTime());
        orderDto.setSs_money(ssMoney);
        orderDto.setYs_money(ysMoney);
        orderDto.setZl_money(zlMoney);
        orderDto.setCashiername(SPHelper.getInstance().getString(Constant.COUNT_NAME));
        orderDto.setCashiernumber(SPHelper.getInstance().getString(Constant.USER_ID));
        orderDto.setShop_id(shopId);
        orderDto.setOrderType(Constant.ORDERTYPE_SALE);
        orderDto.setMaxNo(maxNO);
        orderDto.setSearchTime(GetData.getSearchTime());
        Log.i("GetData.getSearchTime()", "" + GetData.getSearchTime());
        orderDto.setCheckoutTime(GetData.getDataTime());
        orderDto.setDetailTime(GetData.getHHmmssTimet());
        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
        orderDto.setOut_trade_no(out_trade_no);
        orderDto.setPayReturn(aliPayNumber);
        orderDto.setVipNumber(vip);
        orderDto.setIfFinishOrder(Constant.YES);
        orderDto.setUpStatus(Constant.UP_NO);
        /**
         * 给数据库里面添加一条记录
         */

        UploadData.upOrder(getApplicationContext(), orderDto,orderDto.getPayway());
        dao.insert(orderDto);

    }


    private String union_orderid = "";
    public void unionPay(String code,String money,String orderId){
        showDialog("正在请求支付");
        int amount  = (int) (Double.parseDouble(money)*100);
        JSONObject object = new JSONObject();
        try {
            object.put("merchantCode", UnionConfig.merchantCode);
            object.put("terminalCode", UnionConfig.terminalCode);
            object.put("transactionAmount", "1");
            object.put("transactionCurrencyCode", "156");
            object.put("merchantOrderId",UnionConfig.merchantCode+orderId+GetData.getYYMMDDhhmmss());
//            object.put("systemTraceNum", GetData.getHHmmssTime());
            object.put("merchantRemark", GetData.getStringRandom(10));
            object.put("payMode", "E_CASH");
            object.put("payCode", code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("pay", object.toString());
        App.getInstance().getMyOkHttp().post()
                .url(UnionConfig.URL_PAY)
                .jsonParams(object.toString())
                .addHeader("Authorization","OPEN-ACCESS-TOKEN AccessToken="+ SPHelper.getInstance().getString(UnionConfig.TOKEN_MSG))
                .enqueue(new RawResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, String response) {
                        Log.i("pay", response);
                        try {
                            JSONObject json = new JSONObject(response);
                            String errCode = json.getString("errCode");
                            String errInfo = json.getString("errInfo");

                            if (errCode.equals("00")) {
                                union_orderid = json.getString("orderId");
                                Message message = Message.obtain();
                                message.what = PAYSUCCESS;
                                handler.sendMessage(message);
                            } else {
                                Message message = Message.obtain();
                                message.what = PAYFAIL;
                                message.obj = errInfo;
                                handler.sendMessage(message);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, String error_msg) {
                        Log.i("pay", error_msg);
                        Message message = Message.obtain();
                        message.what = TIMEOUT;
                        handler.sendMessage(message);
                    }
                });
    }
    private void setJeDetail(){
        double je = 0;
        for (PayBeen been : payBeens) {
            je += Double.parseDouble(been.getSs());
        }
        tvActual.setText(DoubleSave.doubleSaveTwo(je) + "");
        tvDue2.setText(ysMoney+"");
        if (payBeens.size() == 0) {
            tvChange.setText("0.0");
        } else {
            tvChange.setText(getzlMoney() + "");
        }

    }

    private boolean isHide = false;
    private void hintKbOne() {
//        if (isHide) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 得到InputMethodManager的实例
            if (imm.isActive()) {
                // 如果开启
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_NOT_ALWAYS);

            }
//            isHide = false;
//        }

    }
}
